package com.example.redislearning.controller;

import com.example.redislearning.dto.ApiResponse;
import com.example.redislearning.entity.User;
import com.example.redislearning.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 * 提供用户相关的REST API接口
 */
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ApiResponse<User> register(@Validated @RequestBody User user) {
        try {
            User registeredUser = userService.registerUser(user);
            return ApiResponse.success("注册成功", registeredUser);
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(400, e.getMessage());
        } catch (RuntimeException e) {
            return ApiResponse.error(409, e.getMessage()); // 冲突
        } catch (Exception e) {
            return ApiResponse.error(500, "注册失败: " + e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ApiResponse<User> login(@RequestParam String username, @RequestParam String password) {
        try {
            User user = userService.login(username, password);
            return ApiResponse.success("登录成功", user);
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(400, e.getMessage());
        } catch (RuntimeException e) {
            return ApiResponse.error(401, e.getMessage()); // 未授权
        } catch (Exception e) {
            return ApiResponse.error(500, "登录失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/{userId}")
    public ApiResponse<User> getUser(@PathVariable Integer userId) {
        try {
            User user = userService.getUserById(userId);
            if (user == null) {
                return ApiResponse.error(404, "用户不存在");
            }
            return ApiResponse.success("获取成功", user);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/{userId}")
    public ApiResponse<User> updateUser(@PathVariable Integer userId, @Validated @RequestBody User user) {
        try {
            user.setId(userId);
            User updatedUser = userService.updateUser(user);
            return ApiResponse.success("更新成功", updatedUser);
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(400, e.getMessage());
        } catch (RuntimeException e) {
            return ApiResponse.error(409, e.getMessage()); // 冲突
        } catch (Exception e) {
            return ApiResponse.error(500, "更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{userId}")
    public ApiResponse<Boolean> deleteUser(@PathVariable Integer userId) {
        try {
            boolean deleted = userService.deleteUser(userId);
            if (deleted) {
                return ApiResponse.success("删除成功", true);
            } else {
                return ApiResponse.error(404, "用户不存在");
            }
        } catch (Exception e) {
            return ApiResponse.error(500, "删除失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户积分
     */
    @GetMapping("/{userId}/points")
    public ApiResponse<Integer> getUserPoints(@PathVariable Integer userId) {
        try {
            Integer points = userService.getUserPoints(userId);
            return ApiResponse.success("获取成功", points);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取积分失败: " + e.getMessage());
        }
    }

    /**
     * 增加用户积分
     */
    @PostMapping("/{userId}/points/increment")
    public ApiResponse<Integer> incrementPoints(@PathVariable Integer userId, @RequestParam Integer points) {
        try {
            Integer newPoints = userService.incrementUserPoints(userId, points);
            return ApiResponse.success("积分增加成功", newPoints);
        } catch (Exception e) {
            return ApiResponse.error(500, "增加积分失败: " + e.getMessage());
        }
    }

    /**
     * 减少用户积分
     */
    @PostMapping("/{userId}/points/decrement")
    public ApiResponse<Integer> decrementPoints(@PathVariable Integer userId, @RequestParam Integer points) {
        try {
            Integer newPoints = userService.decrementUserPoints(userId, points);
            return ApiResponse.success("积分减少成功", newPoints);
        } catch (Exception e) {
            return ApiResponse.error(500, "减少积分失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户学习时长
     */
    @GetMapping("/{userId}/study-duration")
    public ApiResponse<Integer> getUserStudyDuration(@PathVariable Integer userId) {
        try {
            Integer duration = userService.getUserStudyDuration(userId);
            return ApiResponse.success("获取成功", duration);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取学习时长失败: " + e.getMessage());
        }
    }

    /**
     * 增加学习时长
     */
    @PostMapping("/{userId}/study-duration/increment")
    public ApiResponse<Integer> incrementStudyDuration(@PathVariable Integer userId, @RequestParam Integer durationMinutes) {
        try {
            Integer newDuration = userService.incrementStudyDuration(userId, durationMinutes);
            return ApiResponse.success("学习时长增加成功", newDuration);
        } catch (Exception e) {
            return ApiResponse.error(500, "增加学习时长失败: " + e.getMessage());
        }
    }

    /**
     * 获取排行榜
     */
    @GetMapping("/leaderboard")
    public ApiResponse<List<Map<String, Object>>> getLeaderboard(
            @RequestParam String type,
            @RequestParam(defaultValue = "10") int limit) {
        try {
            List<Map<String, Object>> leaderboard = userService.getUserLeaderboard(type, limit);
            return ApiResponse.success("获取排行榜成功", leaderboard);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取排行榜失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户统计信息
     */
    @GetMapping("/{userId}/statistics")
    public ApiResponse<Map<String, Object>> getUserStatistics(@PathVariable Integer userId) {
        try {
            Map<String, Object> statistics = userService.getUserStatistics(userId);
            return ApiResponse.success("获取统计信息成功", statistics);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 检查用户名是否存在
     */
    @GetMapping("/check-username")
    public ApiResponse<Boolean> checkUsernameExists(@RequestParam String username) {
        try {
            boolean exists = userService.isUsernameExists(username);
            return ApiResponse.success("检查成功", exists);
        } catch (Exception e) {
            return ApiResponse.error(500, "检查用户名失败: " + e.getMessage());
        }
    }

    /**
     * 检查邮箱是否存在
     */
    @GetMapping("/check-email")
    public ApiResponse<Boolean> checkEmailExists(@RequestParam String email) {
        try {
            boolean exists = userService.isEmailExists(email);
            return ApiResponse.success("检查成功", exists);
        } catch (Exception e) {
            return ApiResponse.error(500, "检查邮箱失败: " + e.getMessage());
        }
    }
}